package com.whsr.readservice.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whsr.readservice.dao.ArticleMapper;
import com.whsr.readservice.dto.ArticleRequest;
import com.whsr.readservice.enums.DownBookEnum;
import com.whsr.readservice.util.HttpClientUtils;
import com.whsr.readservice.util.InterfaceUtil;
import com.whsr.readservice.util.ResultUtil;
import com.whsr.readservice.vo.Article;
import com.whsr.readservice.vo.DownBookMaintain;
import com.whsr.readservice.vo.JobBatch;
import com.whsr.readservice.vo.PageConfigGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleService {
    private static Logger logger = LoggerFactory.getLogger(ArticleService.class);

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DownBookMaintainService downBookMaintainService;

    public JobBatch insertArticles(JobBatch jobBatch){
        List<Integer> bookIds = downBookMaintainService.getBookIdsBystatus(DownBookEnum.WAIT_ARTICLE.getCode());
        logger.info("进入作品基本信息下载接口,书号集合={}", bookIds.toString());
        List<Article> articles = new ArrayList<>();
        List<Integer> updatebookIds = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        Map<String, Integer> categorieMap = categoryService.getCategoryMap();
        Integer complateNum = 0;
        Integer failNum = 0;
        for (Integer bookId : bookIds) {
            articleMapper.deleteArticleByBookId(bookId);
            Article article = new Article();
            param.put("bk_id", bookId.toString());
            JSONObject jsonObject = HttpClientUtils.httpPost(InterfaceUtil.urls[0], param);
            if(jsonObject == null) {
                failNum++;
                continue;
            }
            article.setBookId(Integer.valueOf(jsonObject.getString("bookID"))); // 书号
            article.setBookName(jsonObject.getString("bookName")); // 名称
            article.setBookCover(jsonObject.getString("bookCover")); // 封面
            article.setBookAuthor(jsonObject.getString("bookAuthor")); // 作者
            article.setStatus(jsonObject.getString("status")); // 状态
            article.setWords(Integer.valueOf(jsonObject.getString("words"))); // 字数
            article.setBookIntro(jsonObject.getString("bookIntro")); // 摘要
            article.setBookClass(jsonObject.getString("bookClass")); // 文章类型
            article.setCategoryId(categorieMap.get(jsonObject.getString("bookClass")));
            article.setChapterCount(Integer.valueOf(jsonObject.getString("chapterCount"))); // 章节数
            articles.add(article);
            updatebookIds.add(bookId);
        }
        if(articles.size() > 0){
            int forNum = (articles.size() % InterfaceUtil.MAX_COUNT) > 0 ? (articles.size() / InterfaceUtil.MAX_COUNT) + 1 : (articles.size() / InterfaceUtil.MAX_COUNT);
            for (int i = 0; i < forNum; i++){
                List<Article> newArticles = null;
                List<Integer> newUpdatebookIds = null;
                if(i != forNum -1){
                    newArticles = articles.subList(i*InterfaceUtil.MAX_COUNT, (i+1)*InterfaceUtil.MAX_COUNT);
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, (i+1)*InterfaceUtil.MAX_COUNT);
                } else {
                    newArticles = articles.subList(i*InterfaceUtil.MAX_COUNT, articles.size());
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, articles.size());
                }
                if(newArticles != null && newArticles.size() > 0){
                    try{
                        articleMapper.insertArticles(newArticles);
                        downBookMaintainService.updateDownBookMaintains(newUpdatebookIds, DownBookEnum.WAIT_CHAPTER.getCode());
                        complateNum += newArticles.size();
                    } catch (Exception e){
                          failNum += newArticles.size();
                          logger.info("插入出错" + e);
                          continue;
                    }
                }
            }
        }
        jobBatch.setCompleteArtNum(complateNum);
        jobBatch.setFailArtNum(failNum);
        return jobBatch;
    }

    public List<Article> selectArticlesByArticle(ArticleRequest article) {
        Article u = new Article();
        BeanUtils.copyProperties(article, u);
        return articleMapper.selectArticlesByArticle(u);
    }

    public PageInfo<ArticleRequest> getArticlesByUnion(ArticleRequest article) {
        PageHelper.startPage(article.getPageNo(),article.getPageSize());
        List<ArticleRequest> list = articleMapper.selectArticlesByUnion(article);
        PageInfo<ArticleRequest> pageInfo = new PageInfo<ArticleRequest>(list);
        return pageInfo;
    }


    public int changeArticleByBookId(Integer bookId, Integer dataFlag) {
        if(dataFlag == 1){
            dataFlag = 0;
        } else {
            dataFlag = 1;
        }
        return articleMapper.changeArticleDataFlagByBookId(bookId, dataFlag);
    }

    public List<Map<String, Object>> queryArtByName(String name) {
        return this.articleMapper.queryArtByName(name);
    }

    public Map<String, Object> queryArtByApp(Integer bookId) {
        Article article = articleMapper.selectArticleByAppBookId(bookId);
        Map<String, Object> root = new HashMap<>();
        root.put("bookInfo", article == null ? "" : article);
        return ResultUtil.getResultBySuccess(root);
    }

    public boolean isArtByBookId(Integer bookId) {
        Article article = articleMapper.selectArticleByAppBookId(bookId);
        if(article != null){
            return true;
        }
        return false;
    }
}
